package com.atguigu.gulimall.product.exception;

import com.atguigu.common.utils.FieldErrorMap;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * 集中处理所有异常
 */
@Slf4j
@ResponseBody  //等于 @RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class gulimallControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class) //专门处理controller报过来的异常
    public R handleException(MethodArgumentNotValidException e) {
        log.error("数据校验异常：{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = FieldErrorMap.getFieldErrorMap(bindingResult);
        return R.error(400, "数据校验失败").put("data", map);
    }

//    @ExceptionHandler(value = MismatchedInputException.class)
//    public R handleException(MismatchedInputException e) {
//        log.error("未知异常：{}", e);
//        return R.error(400, "未知异常");
//    }

}
